/**
 * 数据mock
 *
 * @author  li.xiaomei
 */
var url = require('url')
var fs = require('fs')
var path = require('path')
exports.run = function(options, req, res, next) {
  var method = req.method,
    urlObj;

  if (method == 'GET') {
    urlObj = url.parse(req.url, true);
  } else {
    urlObj = url.parse(req.url);
  }

  //不是api|activity开头的数据，直接next
  if (!urlObj.pathname.match(/^\/api|activity|inc/)) {
    next();
    return;
  }

  console.log('====== server 正在尝试接口数据本地mock =======');
  var mockDataFile = path.join(process.cwd(), 'mock', urlObj.pathname) +
    ".json";
  //file exist or not
  fs.access(mockDataFile, fs.F_OK, function(err) {
    if (err) {
      res.setHeader('Content-Type', 'application/json');
      res.end(JSON.stringify({
        "status": "没有找到此文件",
        "notFound": mockDataFile
      }));
      next();
      return;
    }
    var data = fs.readFileSync(mockDataFile, 'utf-8');
    res.setHeader('Content-Type', 'application/json');
    res.end(data);
  });

};
